import React, {useEffect, useState} from 'react';
import './css/Login.css';
import {getCookie, setCookie} from '../utils/cookieUtil'
import {useDispatch} from "react-redux";
import {setIsLogin, setUser} from "../store/modules/userStore";
import instance from "../utils/axiosUtil";
import {message} from 'antd';
import axios from "axios";


const Login = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [email, setEmail] = useState('');
    const [phone, setPhone] = useState('');
    const [error, setError] = useState('');
    const [isRegister, setIsRegister] = useState(false);
    const dispatch = useDispatch();

    useEffect(() => {
        setError('');
        setPhone('');
        setEmail('');
    }, [isRegister]);

    const handleSubmit = (e) => {
        e.preventDefault();
        try {
            axios
                .post('http://localhost:5532/auth/login', {name: username, password: password})
                .then(res => {
                    if (res.data.code === 1) { //登录成功
                        setCookie('auth', res.data.data, 30) //30天自动登录
                        instance.post('http://localhost:5532/auth/autoLogin').then(res => {
                            if (res.data.code === 1) {
                                dispatch(setUser(res.data.data))
                                dispatch(setIsLogin(true));
                                message.success('登录成功');
                            }
                        })
                    } else {
                        setError(res.data.msg)
                    }
                })

        } catch (err) {
            setError('Login failed');
        }
    };

    const handleSubmit_register = async (e) => {
        e.preventDefault();
        try {
            axios.post(
                'http://localhost:5532/auth/register',
                {
                    name: username,
                    email: email,
                    phone: phone,
                    password: password
                }
            ).then(res => {
                if (res.data.code === 1){
                    setCookie('auth', res.data.data, 30) //30天自动登录
                    console.log(getCookie('auth'))
                    instance.post('http://localhost:5532/auth/autoLogin').then(res => {
                        console.log(res)
                        if (res.data.code === 1) {
                            dispatch(setUser(res.data.data));
                            dispatch(setIsLogin(true));
                            message.success('注册成功');
                        }
                    });
                }else {
                    setError(res.data.msg)
                }
            })
        } catch (err) {
            setError('Registration failed');
        }
    };

    return (
        <div className={'login-background'}>
            <div className="login-container"> {/* 添加容器类名 */}
                {!isRegister ? (
                    <form onSubmit={handleSubmit}>
                        <h2>Login</h2>
                        <div>
                            <label>用户</label>
                            <input
                                type="text"
                                placeholder="用户名"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                required
                            />
                        </div>
                        <div>
                            <label>密码</label>
                            <input
                                type="password"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                required
                            />
                        </div>
                        {error && <p className="error">{error}</p>}
                        <button type="submit">登录</button>
                        <div
                            onClick={() => setIsRegister(true)}
                            style={{cursor: 'pointer',textDecoration:'underline',float:'right'}}
                        >注册</div>
                    </form>
                ) : (
                    <form onSubmit={handleSubmit_register}>
                        <h2>Register</h2>
                        <div>
                            <label>用户名</label>
                            <input
                                type="text"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                required
                            />
                        </div>
                        <div>
                            <label>邮箱</label>
                            <input
                                type="email"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                required
                            />
                        </div>
                        <div>
                            <label>电话</label>
                            <input
                                type="tel"
                                value={phone}
                                onChange={(e) => setPhone(e.target.value)}
                                required
                            />
                        </div>
                        <div>
                            <label>密码</label>
                            <input
                                type="password"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                required
                            />
                        </div>
                        {error && <p className="error">{error}</p>}
                        <button type="submit">注册</button>
                        <div
                            onClick={() => setIsRegister(false)}
                            style={{cursor: 'pointer',textDecoration:'underline',float:'right'}}
                        >已有账号，登录</div>
                    </form>
                )}
            </div>
        </div>
    );
};

export default Login;
